using System;
using Bugzproxy;

class ListBugClass { 
  // Helper function - create a sequence of ints.
  static int[] Seq( int start, int count ) {
    int [] res = new int[count];
    while ( count > 0 ) {
      --count;
      res[count] = start + count;
    }
    return res;
  }

  static public int Main( string[] args ) {
    ////////////////////////////////////////////////////////////
    // Use common class to get all arguments
    SimpleAppArgs argParser 
      = new SimpleAppArgs( "ListBugs.exe", 
                           "Program to retrieve multiple bugs (0-100)" );
    // If parsing fails, bail out
    if ( ! argParser.Parse( args ) ) { 
      return 1; 
    }
    Console.WriteLine( "Using server {0}:{1}/{2}", argParser.Host, argParser.Port, argParser.Path );
    // Console.WriteLine( "Using username {0} and password {1}", argParser.User, argParser.Password );
    // Construct server, based on arguments, setup tracer if user set option
    Server server 
      = new Server( argParser.Host, argParser.Port, argParser.Path );
    if ( argParser.Trace ) { 
      server.TraceWriter = System.Console.Out; 
    }
    
    ////////////////////////////////////////////////////////////
    // Real program starts here
    Console.WriteLine( "Id\tAlias\tSummary\tCreated\tChanged" );

    // We may need a login to access this bug, but we try without
    // Note, this is a rather ineffecient way to do things, but
    // currently Bugzilla WebService does not support a way to
    // retrieve what bug ids one can access. So, we start from 1, then
    // proceed until an error occurs (which can be non-existant bug,
    // or access error), or we reach 100 bugs
    int batch = 100;
    int start = 1;
    while ( batch > 0 && start < 100 ) {
      try {
        Bug[] bugs = server.GetBugs( Seq( start, batch ) );
        foreach ( Bug b in bugs ) {
          Console.WriteLine( b.Id + "\t" + b.Alias + "\t" + b.Summary
                 + "\t" + b.Created + "\t" + b.Changed );
        }
        start += batch;
      }
      catch ( Exception e ) {
        // Reduce batch
        batch = batch / 2;
      }
    }
    return 0;
  }
}
